#MQ Interface
#Establishes a connection with a message queue and begins consuming
#messages on its own thread. Connects to John's server if local=True
#otherwise it declares a queue on the localhost.
#
#Written by Tony

import pika, json

class MQInterface:
    
    def __init__(self, cacheRef, local=False, host='dhmq-test1.ibiblio.org', port=5672, user='comp523', password='m8k2pd78n3z4', vhost='/comp523', exchange='datahub'):  
        """If local is True (Default: False), then the queue will be declared on the localhost"""     
        self.cacheRef = cacheRef
        self.local = local
        if (local):
            self.connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
            self.channel = self.connection.channel()
            self.channel.queue_declare(queue='A_Queue')
        else:
            credentials = pika.PlainCredentials(user, password)
            parameters = pika.ConnectionParameters(credentials=credentials, host=host, port=port, virtual_host=vhost)
            self.connection = pika.BlockingConnection(parameters)
            self.channel = self.connection.channel()
            self.exchange = exchange

    
    def callback(self, ch, method, properties, body):
        a = json.loads(body)
        self.cacheRef.deposit(a)
        self.channel.basic_ack(delivery_tag=method.delivery_tag)

    def start_consumption(self, local=False):
        """Establish a connection with MQ and start consuming messages"""
        if (self.local):
            self.channel.basic_consume(self.callback, queue='A_Queue')
        else:
            startMessage = json.dumps({"publish_stats" : True})
            self.channel.basic_publish(exchange=self.exchange, routing_key='permaseed.comp523.control', body=startMessage, properties=pika.BasicProperties(content_type="application/json"))
            self.channel.basic_consume(self.callback, queue='permaseed.comp523.stats')
        
        try:
            self.channel.start_consuming()
        except pika.exceptions.AMQPConnectionError:
            pass
        
    def close_connection(self):
        if (not self.local):
            stopMessage = json.dumps({"publish_stats" : False})
            self.channel.basic_publish(exchange=self.exchange, routing_key='permaseed.comp523.control', body=stopMessage,properties=pika.BasicProperties(content_type="application/json"))
        
        self.connection.close()